package com.medical.controller;


import com.medical.exception.BusinessException;
import com.medical.model.param.Emitters;
import com.medical.model.param.Messages;
import com.medical.service.impl.LLMServiceImpl;
import com.medical.utils.JwtUtils;
import com.medical.domain.R;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 * @author TISNIW
 * @version 1.0
 * @date 2024/8/16 10:58
 * @desc LLMController
 */
@RestController
@Slf4j
@RequestMapping("/llm")
public class LLMController {
    @Autowired
    private LLMServiceImpl llmService;
    /**
     * 聊天
     * @param model
     * @param prompt
     * @param sessionId
     * @param think
     * @return
     */
    @GetMapping("/chat")
    public R<String> chat(@RequestParam String model, @RequestParam String prompt, @RequestParam String sessionId, @RequestParam Boolean think){
        try{
            return R.ok(llmService.chat(model,prompt,sessionId,think));
        }catch (BusinessException e){
            return R.fail(e.getR());
        }
    }//获取会话记录
    @GetMapping("/get")
    public R<List<Messages>> getMessages(@RequestParam(value = "sessionId")String id){
        return R.ok(llmService.getMessages(id));
    }
    /**
     * 获取回复
     * @param sessionId
     * @return
     */
    @GetMapping(value = "/reply", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> getReply(@RequestParam String sessionId) {
        return Flux.create(emitter -> {
            Emitters.addEmitter(sessionId, emitter);
            emitter
                    .onRequest(n -> {
                    })
                    .onDispose(() -> Emitters.removeEmitter(sessionId))
                    .onCancel(() -> Emitters.removeEmitter(sessionId));
        });
    }
    private Long getUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        log.info("原始 token: {}", token);

        if (token == null || !token.startsWith("Bearer ")) {
            throw new RuntimeException("无效的 token");
        }

        // 去除 "Bearer " 前缀 + 去除所有空白字符（包括空格、换行、制表符）
        String cleanToken = token.substring(7).replaceAll("\\s+", "");

        log.info("清理后的 token: {}", cleanToken);

        Long userId = null;
        try {
            userId = JwtUtils.getUserIdFromClaims(cleanToken);
        } catch (Exception e) {
            throw new RuntimeException("Token 解析失败", e);
        }

        return userId;
    }
}
